using System;
using System.IO;
using System.Net;

using octalforty.Componento.SemanticModel;

namespace octalforty.Componento.ComponentModel.Packaging
{
    public class HttpRepositoryBrowser : IRepositoryBrowser
    {
        public HttpRepositoryBrowser()
        {
        }

        public bool CanOpenRepository(Uri repositoryUri)
        {
            return repositoryUri.Scheme.ToLowerInvariant() == "http";
        }

        public Repository OpenRepository(Uri repositoryUri)
        {
            IWebProxy proxy = WebRequest.DefaultWebProxy;
            proxy.Credentials = CredentialCache.DefaultNetworkCredentials;

            WebRequest request = WebRequest.Create(new Uri(repositoryUri, "Packages.cpd"));
            request.Proxy = proxy;

            using(WebResponse response = request.GetResponse())
            {
                using(Stream stream = response.GetResponseStream())
                {
                    using(StreamReader streamReader = new StreamReader(stream, true))
                    {
                        PackageRepositoryDefinitionParser packageRepositoryDefinitionParser = new PackageRepositoryDefinitionParser();
                        return 
                            new Repository(repositoryUri, packageRepositoryDefinitionParser.ParseRepositoryDefinition(streamReader));
                    }
                } // using
            } // using
        }
    }
}
